import React, { useState, useCallback } from 'react';
import html2canvas from 'html2canvas';
import { Toast } from 'antd-mobile';

const useHtml2canvas = ({
  html2canvasContainer,
  shareImgContainer,
  width,
  height,
}) => {
  const [showCanvasImg, setShowCanvasImg] = useState(false);

  /**
   * 根据 window.devicePixelRatio 获取像素比
   * @returns {number}
   */
  const getDpr = () => {
    if (window.devicePixelRatio && window.devicePixelRatio > 1) {
      return window.devicePixelRatio;
    }

    return 1;
  };

  // 生成图片
  const generateImage = useCallback(
    (show = true) => {
      if (!show) {
        setShowCanvasImg(show);
        return;
      }

      // 获取想要转换的dom节点
      var dom = document.getElementById(html2canvasContainer);
      var box = window.getComputedStyle(dom);

      // dom节点计算后宽高
      var width = parseInt(box.width, 10);
      var height = parseInt(box.height, 10);

      // 获取像素比
      var scaleBy = getDpr();

      // 创建自定义的canvas元素
      var canvas = document.createElement('canvas');

      // 设置canvas元素属性宽高为 DOM 节点宽高 * 像素比
      canvas.width = width * scaleBy;
      canvas.height = height * scaleBy;

      // 设置canvas css 宽高为DOM节点宽高
      canvas.style.width = width + 'px';
      canvas.style.height = height + 'px';

      // 获取画笔
      var context = canvas.getContext('2d');

      // 将所有绘制内容放大像素比倍
      context.scale(scaleBy, scaleBy);

      // 设置需要生成的图片的大小，不限于可视区域（即可保存长图）
      var w = dom.offsetWidth || window.innerWidth;
      var h = dom.offsetHeight - 1 || window.innerHeight;
      // console.log('offsetHeight: ', dom.offsetHeight);
      // console.log('offsetWidth: ', dom.offsetWidth);

      Toast.loading('海报生成中...');
      html2canvas(dom, {
        allowTaint: true,
        width: w,
        height: h,
        useCORS: true,
      }).then(function (canvas) {
        // 将canvas转换成图片渲染到页面上
        var url = canvas.toDataURL('image/png'); // base64数据
        var image = new Image();
        image.src = url;
        image.style.width = '100%';
        image.style.height = '100%';
        document.getElementById(shareImgContainer).appendChild(image);
        setShowCanvasImg(show);
        setTimeout(() => {
          Toast.hide();
        }, 200);
      });
    },
    [html2canvasContainer, shareImgContainer]
  );

  return [showCanvasImg, generateImage];
};

export const html2canvasContainer = 'html2canvas';
export const shareImgContainer = 'shareImg';

// 将图片转为base64格式
// 使用第三方图片时会报错
// 当直接通过给img src赋值为第三方图片时，html的渲染及canvas的绘制都是没有问题的，
// 但是生成图片时（使用 canvas.toDataURL），会报跨域的错（对于本地的图片是没有这个问题的）
export const img2base64 = (url, crossOrigin) => {
  return new Promise((resolve) => {
    const img = new Image();

    img.onload = () => {
      const c = document.createElement('canvas');

      c.width = img.naturalWidth;
      c.height = img.naturalHeight;

      const cxt = c.getContext('2d');

      cxt.drawImage(img, 0, 0);

      // 得到图片的base64编码数据
      resolve(c.toDataURL('image/png'));
    };

    // 结合合适的CORS响应头，实现在画布中使用跨域<img>元素的图像
    crossOrigin && img.setAttribute('crossOrigin', crossOrigin);
    img.src = url;
  });
};

export default useHtml2canvas;

// 用法
// const [showImg, setShowImg] = useHtml2canvas({
//   html2canvasContainer, // dom id
//   shareImgContainer, // dom id
// });
